package init

import (
	"fmt"
	"proto-server/basic/config"
	"proto-server/handler/model"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"

	"github.com/go-redis/redis/v8"
	"github.com/spf13/viper"
)

func init() {
	ConfigInit()
	MysqlInit()
	RedisInit()

}

func ConfigInit() {
	var err error
	viper.SetConfigFile("../config/config.yaml")
	err = viper.ReadInConfig()
	if err != nil {
		panic(err)
	}
	err = viper.Unmarshal(&config.ConfigData)
	if err != nil {
		panic(err)
	}
	fmt.Println("数据配置成功", config.ConfigData)
}

func MysqlInit() {
	var err error
	con := config.ConfigData.Mysql

	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		con.User,
		con.Password,
		con.Host,
		con.Port,
		con.Database,
	)
	config.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	fmt.Println("连接成功")
	err = config.DB.AutoMigrate(&model.User{})
	if err != nil {
		panic(err)
	}
	fmt.Println("迁移成功")

}

func RedisInit() {
	var err error
	ca := config.ConfigData.Redis
	cac := fmt.Sprintf("%s:%d", ca.Host, ca.Port)
	config.Rdb = redis.NewClient(&redis.Options{
		Addr:     cac,
		Password: ca.Password, // no password set
		DB:       ca.Database, // use default DB
	})

	err = config.Rdb.Ping(config.Ctx).Err()
	if err != nil {
		panic(err)
	}
	
	fmt.Println("redis成功")

}
